#include "StdAfx.h"
#include "SourceCounterMgr.h"

#ifdef _TCHAR_DEFINED
#define string wstring
#endif

void trim(string& str)
{
	string::size_type begin = str.find_first_not_of(_T(' '));
	string::size_type end = str.find_last_of(_T(' '));
	str = str.substr(begin, end);
}

CSourceCounterMgr::CSourceCounterMgr(void)
{
}

CSourceCounterMgr::~CSourceCounterMgr(void)
{
	for (CVecCountMethod::iterator iter = m_vecCountMethods.begin(); 
		iter != m_vecCountMethods.end();
		iter++)
	{
		if (iter->pCounter != NULL)
		{
			delete iter->pCounter;
		}
	}
}

bool CSourceCounterMgr::AddSourceCounter( TCHAR* pszFileExts, CSourceCounterBase *pCounter )
{
	if (NULL == pszFileExts || NULL == pCounter)
	{
		return false;
	}

	string strFileExt(pszFileExts);
	trim(strFileExt);
	if (IsMethodExist(strFileExt))
	{
		return false;
	}

	CountMethod method;
	method.strFileExt = strFileExt;
	method.pCounter = pCounter;

	m_vecCountMethods.push_back(method);

	return true;
}

bool CSourceCounterMgr::CountDirectory( TCHAR* pszDirectory, int &nBlankLines, int &nCommentLines, int &nCodeLines )
{
	return true;
}

bool CSourceCounterMgr::CountFile( TCHAR* pszFile, int &nBlankLines, int &nCommentLines, int &nCodeLines )
{
	string strFile(pszFile);
	trim(strFile);
	
	string::size_type begin = strFile.find_last_of(_T('.'));
	string strExt = strFile.substr(begin + 1);
	CSourceCounterBase *pCounter = GetCountMethod(strExt);
	if (NULL == pCounter)
	{
		return false;
	}

	return pCounter->CountFile(pszFile, nBlankLines, nCodeLines, nCommentLines);
}

bool CSourceCounterMgr::IsMethodExist( string& strFileExt )
{
	trim(strFileExt);
	for (CVecCountMethod::iterator iter = m_vecCountMethods.begin(); iter != m_vecCountMethods.end(); iter++)
	{
		if (iter->strFileExt.find(strFileExt) != string::npos)
		{
			return true;
		}
	}

	return false;
}

CSourceCounterBase* CSourceCounterMgr::GetCountMethod( string& strFileExt )
{
	for (CVecCountMethod::iterator iter = m_vecCountMethods.begin(); iter != m_vecCountMethods.end(); iter++)
	{
		if (iter->strFileExt.find(strFileExt) != string::npos)
		{
			return iter->pCounter;
		}
	}

	return NULL;
}

#undef string